package com.shujia.redis;

import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.sql.*;

public class RedisCache {

    Connection connection;
    Jedis jedis;

    @Before
    public void init() throws Exception {


        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection("jdbc:mysql://node1:3306/student", "root", "123456");


        jedis = new Jedis("node3", 6379);
    }

    /**
     * 不适用缓存
     */
    @Test
    public void query1() throws SQLException {
        int id = 1;
        String sql = "select * from weibo where id=?";

        //预编译sql执行器   防止sql注入
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, id);

        ResultSet resultSet = preparedStatement.executeQuery();


        if (resultSet.next()) {

            int id1 = resultSet.getInt("id");
            String context = resultSet.getString("context");

            WeiBo weiBo = new WeiBo(id1, context);

            System.out.println(weiBo);
        }

    }


    /**
     * 使用缓冲
     */

    @Test
    public void queryCache() throws Exception {

        //需要查询的微博编号
        int id = 1;

        long start = System.currentTimeMillis();
        WeiBo weibo = query(id);
        System.out.println(weibo);
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }


    public WeiBo query(int id) throws Exception {


        String cacheTable = "weibo_cache";
        /**
         *
         * 1、先取缓冲拆线呢
         *
         */

        String key = cacheTable + ":" + id;
        //获取微博
        String value = jedis.get(key);

        if (value != null) {

            //更新过期时间
            jedis.expire(key, 10);

            //返回数据
            return new WeiBo(id, value);
        } else {

            WeiBo weiBo = null;

            //如果redis中没有这条微博，再查询mysql

            String sql = "select * from weibo where id=?";

            //预编译sql执行器   防止sql注入
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, id);

            ResultSet resultSet = preparedStatement.executeQuery();


            if (resultSet.next()) {

                int id1 = resultSet.getInt("id");
                String context = resultSet.getString("context");

                weiBo = new WeiBo(id1, context);

            }


            if (weiBo != null) {
                // 将微博保存到redis中   设置过期时间
                jedis.setex(key, 10, weiBo.getContext());

            }

            //返回结果
            return weiBo;
        }

    }

}
